/**
 * lib/aes
 *
 * @see https://github.com/keel/aes-cross/tree/master/info-cn
 */

const crypto = require('crypto');
const fsp = require('fs-extra');

const algorithm = 'aes-256-cbc';

const aes = {
    process(data, key, type = 'encryption') {
        const keyBuf = new Buffer(Array(32));
        const ivBuf = new Buffer(Array(16));

        keyBuf.write(key);

        const cipher = type === 'encryption'
            ? crypto.createCipheriv(algorithm, keyBuf, ivBuf)
            : crypto.createDecipheriv(algorithm, keyBuf, ivBuf);

        cipher.setAutoPadding(true);

        if(!Buffer.isBuffer(data)) {
            data = new Buffer(data);
        }

        const buf = Buffer.concat([
            cipher.update(data),
            cipher.final()
        ]);

        return buf;
    },

    encryption(data, key) {
        return this.process(data, key, 'encryption');
    },
    decryption(data, key) {
        return this.process(data, key, 'decryption');
    },
    encryptionFile(src, key) {
        return fsp.readFile(src)
        .then(buf => {
            return this.encryption(buf, key);
        });
    },
    decryptionFile(src, key) {
        return fsp.readFile(src)
        .then(buf => {
            return this.decryption(buf, key);
        });
    }
};

module.exports = aes;

// // const key = '12345678901234561234567890123456';
// const key = '1234567890123456';
// const text = 'hello world.';

// let buf = aes.encryption(text, key);

// console.log(buf.toString('base64'));
